package com.eightbears.beboy.ui.merchant.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopAccountAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.picker.DatePicker;
import com.eightbears.beboy.entity.ShopAccountEntity;
import com.eightbears.beboy.entity.status.Status_Error;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_CURRENTACCOUNT;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;

public class ShopAccountActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    LinearLayout view_empty;

    private TextView tv_account;
    private TextView tv_date;
    private TextView tv_in;
    private View view_data_title;
    LinearLayout ll_calendar;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private String selTime;
    private String startTime;
    private String endTime;
    private String shopId;
    private boolean selectTile = false;

    private ShopAccountAdapter shopAccountAdapter;
    private ShopAccountEntity shopAccountEntity;
    private DatePicker picker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_account);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        showDateSel();
        initAdapter();

    }

    @Override
    protected void initData() {
        tv_title.setText(R.string.text_shop_account_title);
        startTime = CommonUtils.getStartTimeOfMonth();
        endTime = CommonUtils.getEndTimeOfMonth();
        shopId = SPUtil.getUser().getData().getShops().get(0).getShop_id();
        getData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        shopAccountAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                picker.show();
            }
        });
    }

    @OnClick(R.id.ll_back) void back(){
        finish();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        shopAccountAdapter = new ShopAccountAdapter();
        shopAccountAdapter.openLoadAnimation();
        shopAccountAdapter.addHeaderView(getHeaderView());
        shopAccountAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(shopAccountAdapter);
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.head_shop_account, null);
        tv_account = (TextView) view.findViewById(R.id.tv_account);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        tv_in = (TextView) view.findViewById(R.id.tv_in);
        ll_calendar = (LinearLayout) view.findViewById(R.id.ll_calendar);
        view_data_title = view.findViewById(R.id.view_data_title);
        return view;
    }

    private void initHeadViewData() {

        String date, totalBalance, balance;
        totalBalance = String.format(getString(R.string.text_price),
                shopAccountEntity.getData().getTotal_income());
        if(shopAccountEntity.getData().getIncome().size() > 0) {
            balance = String.format(getString(R.string.text_price),
                    shopAccountEntity.getData().getIncome().get(0).getBalance());
            date = CommonUtils.Date2TimeStamp(shopAccountEntity.getData().getIncome().get(0).getDate(), "yyyy-MM-dd");
            date = CommonUtils.TimeStamp2Date(date, "yyyy年MM月dd日");
        } else {
            balance = "0.00";
            date = CommonUtils.TimeStamp2Date(String.valueOf(System.currentTimeMillis() / 1000), "yyyy年MM月dd日");
        }

        tv_account.setText(totalBalance);
        tv_in.setText(balance);
        if(null != selTime) {
            tv_date.setText(selTime);
        } else {
            tv_date.setText(date);
        }


        ll_calendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                picker.show();
            }
        });

    }

    private void showDateSel() {
        if (picker == null) {
            picker = new DatePicker(ShopAccountActivity.this);
            picker.setUseWeight(true);
            picker.setCanceledOnTouchOutside(true);
            picker.setRangeStart(1990, 1, 1);
            picker.setRangeEnd(2111, 1, 1);
            picker.setSelectedItem(2017, CommonUtils.getDate()[1], CommonUtils.getDate()[2]);
            picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {
                    selDate(year, month, day);
                }
            });
        }
    }

    private void selDate(String year, String month, String day) {
        String start = year + "-" + month + "-" + day + " " + "00:00:00";
        String end = year + "-" + month + "-" + day + " " + "23:59:59";
        startTime = CommonUtils.dateToStamp(start, "yyyy-MM-dd HH:mm:ss");
        endTime = CommonUtils.dateToStamp(end, "yyyy-MM-dd HH:mm:ss");
        selTime = year + "年" + month + "月" + day + "日";
        tv_date.setText(selTime);
        page = 1;
        selectTile = true;
        getData();
    }


    private void getData() {
        OkHttpUtils.get().url(URL_USER_CURRENTACCOUNT + shopId)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", "2")
                .addParams("page", String.valueOf(page))
                .addParams("size", PARAMS_PAGE_SIZE)
                .addParams("start_at", startTime)
                .addParams("end_at", endTime)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                shopAccountEntity = GsonUtil.fromJson(response, ShopAccountEntity.class);
                if(!selectTile)
                    classifyItem();

                if (shopAccountEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    initHeadViewData();
                    isEnd = shopAccountEntity.getData().getIs_end();
                    if (page == 1) {
                        shopAccountAdapter.setNewData(shopAccountEntity.getData().getList());
                        if (shopAccountEntity.getData().getList().size() == 0) {
                            view_data_title.setVisibility(View.VISIBLE);
                            view_empty.setVisibility(View.VISIBLE);
                        } else
                            view_empty.setVisibility(View.GONE);
                    } else {
                        shopAccountAdapter.addData(shopAccountEntity.getData().getList());
                        shopAccountAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    private void classifyItem(){
        List<ShopAccountEntity.AccountBalance> temp = shopAccountEntity.getData().getList();
        if(temp.size() != 0) {
            for (int i = 0; i < shopAccountEntity.getData().getIncome().size(); i++){
                for (int j = 0; j < temp.size(); j++) {
                    String date = CommonUtils.TimeStamp2Date(temp.get(j).getCreated_at(), "yyyy-MM-dd");
                    if(shopAccountEntity.getData().getIncome().get(i).getDate().equals(date)) {
                        shopAccountEntity.getData().getList().get(j)
                                .setTotalBalance(shopAccountEntity.getData().getIncome().get(i).getBalance());
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onRefresh() {
        shopAccountAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                shopAccountAdapter.getData().clear();
                getData();
                shopAccountAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    shopAccountAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(ShopAccountActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        shopAccountAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
